package com.wxzl.community.common.widget

import android.content.Context
import android.os.Parcelable
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.widget.FrameLayout
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.wxzl.community.common.R
import com.wxzl.community.common.databinding.ViewCityIndexBinding
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import com.drake.brv.utils.divider
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.parcelize.Parcelize


/**
 * @Author: LiaoZhongKai
 * @Date: 2021/5/11 16:46
 * @Description: 城市选择View
 */
class CityIndexView(context: Context, attributeSet: AttributeSet) : FrameLayout(
    context,
    attributeSet
) {

    private lateinit var mBinding: ViewCityIndexBinding
    private var mIndexList = mutableListOf("A", "B", "C", "D", "E", "F", "G", "H", "I",
        "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
        "W", "X", "Y", "Z")
    private var mCityList = mutableListOf<Any>()
    private var mOnCitySelectListener: OnCitySelectListener? = null

    init {
        initView()
        initData()
        setCityRV()
        setIndexRV()
    }

    private fun initView() {
        mBinding = DataBindingUtil.inflate<ViewCityIndexBinding>(
            LayoutInflater.from(context),
            R.layout.view_city_index, this, true
        )
    }

    private fun getCityJson(): String {
        val strBuilder = StringBuilder()
        val assetManager = context.assets
        try {
            val bufferedReader = BufferedReader(
                InputStreamReader(
                    assetManager.open("city.json"), "utf-8"
                )
            )
            var line: String? = null
            do {
                line = bufferedReader.readLine()
                if (line == null) break
                strBuilder.append(line)
            } while (true)
            bufferedReader.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return strBuilder.toString()
    }

    private fun initData(){
        val gson = Gson()
        val type = object :TypeToken<Map<String,MutableList<City>>>(){}.type
        val map = gson.fromJson<Map<String,MutableList<City>>>(getCityJson(),type)
        if (map != null){
            for ((key,value) in map){
                mCityList.add(key)
                value.forEach {
                    mCityList.add(it)
                }
            }
        }
    }

    private fun getCityData(): MutableList<Any>{
        return mCityList
    }

    private fun getIndexData(): MutableList<String>{

        return mIndexList
    }

    @Parcelize
    data class City(var id: String, var name: String, var index: String? = null): Parcelable

    private fun setCityRV(){
        mBinding.cityRv.apply {
            divider {
                setDivider(1,true)
                setMargin(15,15,true)
            }.setup {
                addType<String>(R.layout.item_view_city_char)
                addType<City>(R.layout.item_view_city_name)
                onClick(R.id.name_tv){
                    mOnCitySelectListener?.onCitySelect((getModel() as City).name)
                }
            }
        }.models = getCityData()
    }

    private fun setIndexRV(){
        mBinding.indexRv.divider {
            setDivider(1,true)
            setMargin(15,15,true)
        }.setup {
            addType<String>(R.layout.item_view_city_index)
            onClick(R.id.item_fl){
                mBinding.cityRv.models?.forEachIndexed { index, bean ->
                    if (bean is String && bean == (getModel() as String)){
                        scrollToTop(index)
                        return@forEachIndexed
                    }
                }
            }
        }.models = getIndexData()
    }

    private fun scrollToTop(position: Int){
        val layoutManager: LinearLayoutManager = mBinding.cityRv.layoutManager as LinearLayoutManager
        layoutManager.scrollToPositionWithOffset(position,0)
    }

    interface OnCitySelectListener{
        fun onCitySelect(cityName: String)
    }

    fun setCitySelectListener(listener: OnCitySelectListener){
        mOnCitySelectListener = listener
    }

}